<template>
  <div class="AiChatview">
    <div class="left">
      <div class="leftheader">
        <div class="leftheaderl">
          <img src="../assets/AI-logo.png" alt="" class="leftheaderlimg" />
        </div>
        <div class="leftheaderr">汤圆</div>
      </div>
      <div class="leftbody">
        <div
          :class="{ selected: selectNum === index }"
          v-for="(item, index) in sessions"
          :key="index"
          @click="selectTap(index)"
        >
          <div class="leftbodylist1">
            <img class="leftbodylist11" :src="item.icon" alt="" />
          </div>
          <div class="leftbodylist2">
          <div class="session-title">{{ item.title || '新建会话' }}</div>
          <div class="session-time">{{ item.createTime || '' }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="rightheader">
        <div class="rh1"></div>
        <div class="rh2">
          <div class="rh21"></div>
          <div class="rh22">
            <img src="../assets/touxiang1.png" alt="" class="rh221" />
          </div>
        </div>
        <div class="rh23">
          <el-dropdown>
            <span class="el-dropdown-link">
              栖星
              <el-icon class="el-icon--eight">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="PersonView">个人中心</el-dropdown-item>
                <el-dropdown-item @click="HomePage">返回首页</el-dropdown-item>
                <el-dropdown-item>修改密码</el-dropdown-item>
                <el-dropdown-item divided @click="LoginView">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="rightbody">

        <div v-if="showLoginPrompt" class="login-prompt-container">
          <div class="login-prompt">
            <div class="prompt-icon">🔒</div>
            <h3 class="prompt-title">请先登录</h3>
            <p class="prompt-message">登录后即可使用汤圆AI智能对话功能</p>
            <button @click="goToLogin" class="prompt-button">立即登录</button>
          </div>
        </div>

        <div v-else  class="rb1">
          <div class="rb11" v-if="sendStatus == 1">亲爱的志愿者同志，你好呀</div>
          <div class="rBody11" ref="scroll" v-if="sendStatus==0">

            <div class="message-loading" v-if="isLoading">正在思考中...</div>
            <div class="message-container" v-for="(item, index) in list1" :key="index">
              <div 
                :class="item.role === 'bot' ? 'message-bot' : 'message-user'"
              >
                <div class="message-content">
                  {{ item.content }}
                <span v-if="item.isStreaming" class="typing-indicator">...</span>
                </div>
              </div>
            </div>
          </div>

           <div class="rb12" :class="{ 'rb12-center': sendStatus === 1, 'rb12-bottom': sendStatus === 0 }">
            <div style="height: 10px"></div>
            <div class="rb121">
              <textarea
                v-model="textarea2"
                @keyup.enter="sendMsg"
                placeholder="请输入您想问的问题"
                class="textarea2"
              ></textarea>
            </div>
            <div class="rb122">
              <div class="rb1221"></div>
              <div class="rb1222">
                <img
                  src="../assets/jiantou.png"
                  @click="sendMsg"
                  class="rb1222"
                  mode="widthfix"
                />
              </div>
            </div>
            <div class="height20px"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import shizhong from "../assets/shizhong.png";
import sousuo from "../assets/sousuo2.png";
import tianjia from "../assets/tianjia.png";
import { ArrowDown } from '@element-plus/icons-vue'
export default {
  name: "AiChatview",
  components: {
    ArrowDown
  },
  data() {
    return {
      textarea2: "",
      sendStatus: 1,
      selectNum: 0,
      currentConventionId: null, 
      list1: [], 
      sessions: [
        {
          title: "新建会话",
          icon: tianjia,
          id: "new-session"
        },
        {
          title: "历史会话",
          icon: shizhong,
        },
        {
          title: "AI 搜索",
          icon: sousuo,
        },
      ], 
      
      user: null,
      isLoading: false,
      showLoginPrompt: false,
      defaultIcon: "https://picsum.photos/30/30"
    };
  },
  methods: {
    createNewSession() {
      this.currentConventionId = "new-session";
      this.list1 = [];
      this.selectNum = 0;
    },
    async selectTap(index) {
      this.selectNum = index;
      const session = this.sessions[index];
      if (!session) return;
      if (session.id === "new-session") {
          this.createNewSession();
          return;
        }

    this.currentConventionId = session.id;
    try {
      const res = await this.$axios.get('/api/chat/history', {
        params: { conventionId: session.id }
      });
      this.list1 = res.data; 
      this.scrollToBottom(); 
    } catch (err) {
      console.error('加载历史消息失败', err);
      this.$message.error('加载历史消息失败');
    }
  },

  async sendMsg() {
      const content = this.textarea2.trim();
      if (!content) {
        this.$message.warning('请输入内容');
        return;
      }
      if (!this.user?.id) {
        this.$message.error('请先登录');
        return;
      }
      this.sendStatus = 0; 
      let conventionId = this.currentConventionId;
      const isNewSession = conventionId === "new-session";
      if (isNewSession) {
        conventionId = null;
      }
      
      this.list1.push({ role: 'user', content });
      this.textarea2 = '';
      this.isLoading = true;
      this.scrollToBottom();
      
      try {
        const res = await this.$axios.post('/api/chat', {
          content: content,
          user: this.user,
          conventionId: conventionId
        });
        
        const aiContent = res.data.content;
        this.currentConventionId = res.data.conventionId;
        this.list1.push({ role: 'bot', content: aiContent });
        
        if (isNewSession) {
          const newSession = {
            id: this.currentConventionId,
            title: content.slice(0, 20),
            createTime: new Date().toLocaleString()
          };
          this.sessions.splice(1, 0, newSession);
          this.selectNum = 1;
        }
      } catch (err) {
        this.list1.push({ role: 'bot', content: '抱歉，消息发送失败，请重试' });
        console.error('消息发送失败', err);
        this.$message.error('消息发送失败');
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const scrollEl = this.$refs.scroll;
        if (scrollEl) {
      scrollEl.scrollTop = scrollEl.scrollHeight;
    }
      });
    },
    getBgStyle(item) {
      if (item.role === 'bot') {
        return { backgroundColor: '#e6f7ff' };
      } else {
        return { backgroundColor: '#f0f9ff' };
      }
    },
    HomePage() {
    this.$router.push('/'); // 首页路由路径，根据实际项目修改
  },
    PersonView() {
    this.$router.push('/PersonView');
  },
    LoginView() {
      sessionStorage.setItem("LoginView", "1");
      this.user = null;
      this.$router.push("/");
    },
    logout() {
    },
  },
  mounted() {
  const userStr = sessionStorage.getItem('user');
  if (userStr) {
    this.user = JSON.parse(userStr);
    this.sendStatus = 1; 
  } else {
    this.$router.push('/login');
  }
}
};
</script>

<style scoped>
.AiChatview {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  border-radius: 10px;
}
.left {
  height: 100%;
  width: 150px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  background-color: #dddbdb39;
}
.leftheader {
  background-color: #e0f6ff;
  height: 90px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-color: #fff;
}
.leftheaderlimg {
  height: 40px;
  width: 40px;
  border-radius: 10px;
  margin-right: 15px;
}
.leftheaderr {
  font-size: 28px;
  font-family: "SimSun", serif;
  font-weight: 900;
}
.leftbody {
  width: 100%;
  flex: 1;
  background-color: #e0f6ff;
  display: flex;
  flex-direction: column;
  padding: 10px 0;
}
.leftbodylist1 {
  margin-right: 10px;
}
.leftbody > div {
  width: 100%;
  padding: 10px 15px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-left: 0px;
  margin-top: 20px;
}
.leftbody > div.selected {
  background-color: #f0f7ff;
  border-radius: 8px;
}
.leftbody > div {
  transition: background-color 0.2s;
}
.leftbodylist11 {
  height: 30px;
  width: 30px;
  border-radius: 15px;
}
.right {
  height: 100%;
  flex: 1;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}
.rightheader {
  width: 100%;
  height: 90px;
  background-color: #e0f6ff;
  display: flex;
  align-items: center;
}
.rh1 {
  width: 1px;
  height: 90px;
  background-color: #e0f6ff;
}
.rh2 {
  display: flex;
  align-items: center;
  flex: 1;
  background-color: #e0f6ff;
}
.rh21 {
  flex: 1;
}
.rh22 {
  width: 40px;
  height: 40px;
  margin-right: 15px;
}
.rh221 {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.rh23 {
  height: 100%;
  margin-right: 50px;
  margin-left: 10px;
  background-color: #e0f6ff;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: #e0f6ff;
  cursor: pointer;
}
.rh23:hover {
  background-color: rgba(255, 255, 255, 0.3);
}
.el-dropdown-link {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
  font-family: Arial, Helvetica, sans-serif;
}

.el-icon--eight {
  font-size: 14px;
  color: #666;
}
.rightbody {
  flex: 1;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px; /* 增加内边距，避免内容贴边 */
  box-sizing: border-box; 
}
.rb1 {
  width: 700px;
  max-width: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}
.rb11 {
  width: 100%;
  font-size: 24px;
  font-weight: 500;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}
.rb12 {
  /* margin-top: 15px; */
  width: 700px;
  /* height: 120px; */
  background-color: #fff;
  border-radius: 15px;
  border: solid 1px #cfcfcf;
  display: flex;
  flex-direction: column;
  padding: 10px;
}
.rb12-center {
  /* 使用绝对定位居中 */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  /* 确保在其他内容上方 */
  z-index: 10;
}

/* sendStatus=0时，输入框在底部 */
.rb12-bottom {
  /* 固定在底部 */
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  /* 确保宽度适应 */
  width: 700px;
  max-width: 90%;
}

.rb121 {
  flex: 1;
  width: 100%;
}
.rb122 {
  height: 25px;
  width: 100%;
  display: flex;
}
.rb1221 {
  flex: 1;
}
.rb1222 {
  width: 27px;
  align-items: center;
  border-radius: 20px;
  margin-bottom: 0px;
}
.textarea2 {
  padding: 0 10px 10px 10px;
  width: 96%;
  border: none;
  outline: none;
}
.usercss {
  background-color: #f0f9ff;
  border-radius: 10px;
  padding: 10px;
  margin: 5px 0;
  text-align: left;
}
.botcss {
  background-color: #e6f7ff;
  border-radius: 10px;
  padding: 10px 15px;
  margin: 8px 0;
  text-align: right;
  display: inline-block;
  max-width: 80%;
  margin-left: auto;
}
.a1a {
  display: none;
}

.a2a.center,
.a3a.center {
  word-wrap: break-word;
  white-space: normal;
  font-size: 16px;
}
.LoginView-btn {
  position: fixed;
  right: 20px;
  bottom: 20px;
  background-color: rgb(7, 118, 165);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  z-index: 999;
}
.LoginView-btn:hover {
  background-color: rgb(10, 148, 207);
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
.rBody11 {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
  max-height: calc(100vh - 210px);
}

.rBody11::-webkit-scrollbar {
  width: 6px; /* 滚动条宽度 */
}
.rBody11::-webkit-scrollbar-thumb {
  background-color: #ddd; /* 滚动条颜色 */
  border-radius: 3px; /* 滚动条圆角 */
}
.rBody11::-webkit-scrollbar-track {
  background-color: #f5f5f5; /* 滚动条轨道颜色 */
}

/* 消息加载样式 */
.message-loading {
  text-align: center;
  padding: 10px;
  color: #666;
  font-size: 14px;
}

/* 每条消息的容器 */
.message-container {
  margin: 8px 0;
  display: flex;
}

/* AI消息样式 - 靠左 */
.message-bot {
  align-self: flex-start;
  max-width: 80%;
}

/* 用户消息样式 - 靠右 */
.message-user {
  margin-left: auto;
  align-self: flex-end;
  max-width: 80%;
}

/* 消息内容样式 */
.message-content {
  padding: 10px 15px;
  border-radius: 10px;
  word-wrap: break-word;
  white-space: normal;
  font-size: 16px;
  line-height: 1.5;
}

/* AI消息气泡样式 */
.message-bot .message-content {
  background-color: #e6f7ff;
  border-top-left-radius: 4px; /* 左上角稍微圆角，区分方向 */
}

/* 用户消息气泡样式 */
.message-user .message-content {
  background-color: #f0f9ff;
  border-top-right-radius: 4px; /* 右上角稍微圆角，区分方向 */
}

</style>
